package com.gc;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by Lxk on 2019/2/26.
 */
class Counter {

    private int count = 0;

    Lock lock = new ReentrantLock();

    public void add(){
        lock.lock();
        try{
            count++;
            System.out.println("当前线程为:" + Thread.currentThread().getName() + ",计数器的值为:" + count);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

}

class ThreadRun extends Thread {

    private Counter counter;

    public ThreadRun(Counter counter){
        this.counter = counter;
    }

    public void run(){
        try{
            for(int i = 0;i <= 100; i++){
                counter.add();
                Thread.sleep(10);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}





public class ReentrantLockTest {

    public static void main(String[] args){
        Counter counter = new Counter();
        ThreadRun threadA = new ThreadRun(counter);
        ThreadRun threadB = new ThreadRun(counter);
        threadA.start();
        threadB.start();
    }

}
